package com.link.base.base.sms.controller;

import com.link.base.sms.model.Signature;
import com.link.base.sms.model.SmsAccntLine;
import com.link.base.sms.model.SmsSend;
import com.link.base.sms.model.Template;
import com.link.base.user.model.CoreUser;
import com.link.base.base.sms.model.AccntGrouping;
import com.link.base.base.sms.model.SmsAccntLineDTO;
import com.link.base.base.sms.service.*;
import com.link.core.cllog.LCLogger;
import com.link.base.loyalty.member.model.Member;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.modules.export.ExportFactory;
import com.link.core.modules.export.ExportWriter;
import com.link.core.util.SessionUtil;
import com.link.core.util.StringUtils;
import com.link.core.util.UserUtil;
import com.link.base.base.sms.service.*;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 消息模板Controller
 * @author liulu
 * @zhushi:
 */

@Controller
@RequestMapping("/link/smsSend")
public class SmsSendController extends BasicController<SmsSend> {

    @Resource
    private SmsSendService smsSendService;
    @Resource
    private TemplateService templateService;
    @Resource
    private SmsAccntLineService smsAccntLineService;
    @Resource
    private TemparameterService temparameterService;
    @Resource
    private AccntGroupingService accntGroupingService;
    @Resource
    private SignatureService signatureService;


    @Override
    public BasicService<SmsSend> getBasicService() throws Exception {
        return smsSendService;

    }

    /**
     * @author liulu
     * @zhushi: 新建短信
     */
    @RequestMapping(value = "/inserte")
    @ResponseBody
    public Map<String, Object> inserte() {
        Map<String, Object> result = new HashMap<>(4);
        try {
            Long smsId = smsSendService.insertSms(new SmsSend());
            result.put("SendSmsId", smsId.toString());
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * @author liulu
     * @zhushi: 根据条件筛选客户
     */
    @RequestMapping(value = "/queryAccontByCondition")
    @ResponseBody
    public Map<String, Object> queryAccontByCondition(@RequestBody AccntGrouping entity) {
        Map<String, Object> result = new HashMap<>(6);
        SmsAccntLineDTO smsAccntLineDTO = new SmsAccntLineDTO();
        try {
            if (entity.getAccntConditionList().isEmpty()) {
                result.put("success", true);
                result.put("total", 0);
                return result;
            }
            accntGroupingService.analysisConditionWithoutQps(entity, smsAccntLineDTO);
            smsAccntLineDTO.setOnlyCountFlag(true);
            List<SmsAccntLine> smsAccntLines = smsAccntLineService.queryByFiltrateExamplePage(smsAccntLineDTO);
            result.put("success", true);
            result.put("total", smsAccntLines.get(0).getTotal());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsAccntLine>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * @author liulu
     * @zhushi: 新建短信，发送短信
     */
    @ResponseBody
    @RequestMapping("/sendSms")
    public Map<String, Object> sendSms(@JsonParam QueryParams qps, @JsonParam SmsSend smsSend, @JsonParam AccntGrouping accntGrouping) {
        Map<String, Object> result = new HashMap<>(8);
        try {
            Long sendSmsId = Long.parseLong(SessionUtil.getAttribute("SendSmsId"));
            smsSend.setId(sendSmsId);
            Template tem = templateService.queryById(smsSend.getTemplateId());
            smsSend.setTemplate(tem);
            Long tempId = temparameterService.inserbyTemplate(smsSend);
            smsSend.setTemparameterId(tempId);
            Signature signature = signatureService.queryById(smsSend.getSignatureId());
            smsSend.setSigText(signature.getText());

            SmsAccntLineDTO smsAccntLineDTO = new SmsAccntLineDTO();
            accntGroupingService.analysisConditionWithoutQps(accntGrouping, smsAccntLineDTO);
            //根据手机号去重客户，建立短信-客户关联关系，返回去重后客户数量
            int smsCount = smsSendService.addSendAcctRemoveDup(smsAccntLineDTO, sendSmsId, 200);
            smsSend.setSendPeopleCount(smsCount);
            smsSendService.update(smsSend);

            String imidiately = "Imidiately";
            if (imidiately.equals(smsSend.getSendMode())) {
                smsSendService.sendSms(smsSend);
            }
            result.put("newRow", smsSend);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsSend>());
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 取消发送时清空短信记录
     */
    @RequestMapping("/cancelSms")
    @ResponseBody
    public Map<String, Object> cancelSms(@JsonParam SmsSend entity, HttpSession session) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>(4);
        String sendSmsId = SessionUtil.getAttribute("SendSmsId");
        if (!StringUtils.isNull(sendSmsId)) {
            // 删除短信
            entity.setId(Long.parseLong(sendSmsId));
            smsSendService.deleteById(entity);
            // 清除session
            SessionUtil.removeAttribute("SendSmsId");
        }
        result.put("success", true);
        return result;
    }

    /**
     * 清空客户
     */
    @RequestMapping(value = "/deleteBySmsId")
    @ResponseBody
    public Map<String, Object> deleteBySmsId(HttpSession session,
                                             HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        try {

            String sendSmsId = SessionUtil.getAttribute("SendSmsId");
            if (!StringUtils.isNull(sendSmsId)) {
                // 删除与客户的关联关系
                smsSendService.delBySmsId(Long.parseLong(sendSmsId));
                result.put("success", true);
            } else {
                result.put("success", false);
            }

        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 拿分组数据
     */
    @RequestMapping(value = "/getAccntGroping")
    @ResponseBody
    public Map<String, Object> getAccntGroping(@RequestBody QueryParams qps, HttpSession session,
                                               HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String sendSmsId = SessionUtil.getAttribute("SendSmsId");
        String[] grop = qps.getAttr8();
        try {
            SmsAccntLine accn = new SmsAccntLine();
            List<SmsAccntLine> smsAccntLinelist = new ArrayList<>();
            List<SmsAccntLine> aclist;
            for (int i = 0; i < grop.length; i++) {
                AccntGrouping arr = accntGroupingService.queryById(Long.parseLong(grop[i]));
                SmsAccntLine accnt = new SmsAccntLine();
                accnt.setPageFlag(false);
                accnt.setxAttr65(arr.getId().toString());
                aclist = smsAccntLineService.queryBySendSmsIdExamplePage(accnt);
                aclist = smsAccntLineService.isRepetition(smsAccntLinelist, aclist);
                smsAccntLinelist = smsAccntLineService.addlist(smsAccntLinelist, aclist);
                aclist.clear();
                if (!CollectionUtils.isEmpty(arr.getAccntConditionList())) {
                    QueryParams qp = accntGroupingService.analysisCondition(arr);
                    qp.preDealSecurity(request);
                    SmsAccntLineDTO t = (SmsAccntLineDTO) BasicModel.transformClass(accn, qp);
                    t.setPageFlag(false);
                    aclist = smsAccntLineService.queryByFiltrateExamplePage(t);
                    aclist = this.isRepetition(smsAccntLinelist, aclist);
                    smsAccntLinelist = smsAccntLineService.addlist(smsAccntLinelist, aclist);
                    aclist.clear();
                }
            }

            SmsSend sm = new SmsSend();
            // 清楚以前的关联
            smsSendService.delBySmsId(Long.parseLong(sendSmsId));
            // 设置新的关联
            sm.setSmsAccntLineList(smsAccntLinelist);
            sm.setId(Long.parseLong(sendSmsId));
            smsSendService.addSendAccont(sm);

            qps.preDealSecurity(request);

            List<SmsAccntLine> listaccn = smsAccntLineService.accntLinePage(qps, smsAccntLinelist);
            result.put("rows", listaccn);
            result.put("success", true);
            result.put("total", smsAccntLinelist.size());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 确定数据
     */
    @RequestMapping(value = "/addSendAccnt")
    @ResponseBody
    public Map<String, Object> addSendAccnt(@RequestBody List<SmsAccntLine> smsAccntLineList, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(8);
        String sendSmsId = SessionUtil.getAttribute("SendSmsId");
        try {
            List<SmsAccntLine> aclist;

            SmsAccntLine accnt = new SmsAccntLine();
            accnt.setPageFlag(false);
            accnt.setxAttr64(sendSmsId);
            aclist = smsAccntLineService.queryBySendSmsIdExamplePage(accnt);
            SmsSend sm = new SmsSend();
            // 设置新的关联
            sm.setSmsAccntLineList(smsAccntLineList);
            sm.setId(Long.parseLong(sendSmsId));
            smsSendService.addSendAccont(sm);
            aclist = smsAccntLineService.addlist(aclist, smsAccntLineList);
            QueryParams qps = new QueryParams();
            qps.setPageFlag(true);
            qps.setPage(1);
            qps.setRows(15);
            List<SmsAccntLine> bulist = smsAccntLineService.accntLinePage(qps, aclist);


            result.put("rows", bulist);
            result.put("success", true);
            result.put("total", aclist.size());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * @author liulu
     * @zhushi: 去重
     */
    public List<SmsAccntLine> isRepetition(List<SmsAccntLine> arr, List<SmsAccntLine> brr) {
        if ((!CollectionUtils.isEmpty(arr)) && (!CollectionUtils.isEmpty(brr))) {
            for (SmsAccntLine a1 : arr) {
                for (SmsAccntLine b1 : brr) {
                    if (a1.getId() == b1.getId()) {
                        brr.remove(b1);

                    }
                }
            }
        }

        return brr;
    }

    /**
     * @author liulu
     * @zhushi: 添加
     */
    public List<SmsAccntLine> addlist(List<SmsAccntLine> arr, List<SmsAccntLine> brr) {
        if ((!CollectionUtils.isEmpty(brr))) {
            for (SmsAccntLine smsAccntLine : brr) {
                if (!StringUtils.isNull(smsAccntLine.getMobilePhone1())) {
                    arr.add(smsAccntLine);
                }
            }
        }
        return arr;
    }


    /**
     * 导出效验后消费者 excel 数据
     */

    @RequestMapping(value = "/exportExcelData")
    @ResponseBody
    public Map<String, Object> exportData(SmsAccntLine entity, QueryParams qps, HttpSession session,
                                          HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<String, Object>(6);
        try {
            qps.preDealSecurity(request);
            SmsAccntLine t = (SmsAccntLine) BasicModel.transformClass(entity, qps);
            ExportWriter exportWriter;
            // xlsx
            exportWriter = ExportFactory.Excel2007Instance(qps);
            CoreUser landedUser = UserUtil.getUser();
            t.setAcctType("CUSTOMER");

            t.setOrgId(landedUser.getOrgId());
            String sendSmsId = SessionUtil.getAttribute("SendSmsId");
            while (!qps.getStopExport()) {

                SmsAccntLine accn = new SmsAccntLine();
                accn.setPageFlag(false);
                accn.setxAttr64(sendSmsId);
                List<SmsAccntLine> list = smsAccntLineService.queryBySendSmsIdExamplePage(accn);
                if (qps.getPage() == 1) {
                    qps.setTotal(t.getTotal());
                }

                exportWriter.wirteData(list);
                t.setPage(qps.getPage());
                t.setTotalFlag(qps.getTotalFlag());
            }
            result.put("success", true);
            result.put("url", exportWriter.getUrlPath());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 根据条件筛选微信粉丝客户
     * @author wangdawei
     * @date 2019-02-18
     */
    @RequestMapping(value = "/filterWxAccnt")
    @ResponseBody
    public Map<String, Object> filterWxAccnt(HttpSession session, @RequestBody AccntGrouping entity,
                                                      HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(6);
        SmsAccntLine smsAccntLine = new SmsAccntLine();
        try {
            List<SmsAccntLine> aclist = new ArrayList<>();
            // 解析前端传入的过滤条件
            QueryParams qps = accntGroupingService.analysisCondition(entity);
            qps.preDealSecurity(request);
            SmsAccntLine t = (SmsAccntLine) BasicModel.transformClass(smsAccntLine, qps);
            t.setPageFlag(false);
            // 微信公众号
            t.setxAttr40(entity.getWechatNum());
            aclist = smsAccntLineService.filterWxAccntByExamplePage(t);
            Long sendSmsId = smsSendService.insertSms(new SmsSend());
            // 删除原有的模板消息与客户关联，防止重复。
            smsSendService.delBySmsId(sendSmsId);
            // 设置新的关联
            SmsSend smsSend = new SmsSend();
            smsSend.setId(sendSmsId);
            smsSend.setSmsAccntLineList(aclist);
            smsSendService.addSendAccont(smsSend);
            qps.setPageFlag(true);
            //  重新设置分页
            List<SmsAccntLine> ac = smsAccntLineService.accntLinePage(qps, aclist);
            //设置总数
            result.put("success", true);
            result.put("rows", ac);
            result.put("total", aclist.size());
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsAccntLine>());
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<SmsAccntLine>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员模块——消息发送
     */
    @RequestMapping(value = "/microSendSms")
    @ResponseBody
    public Map<String, Object> microSendSms(@RequestBody SmsSend smsSend, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {

        Map<String, Object> result = new HashMap<>();
        try {
            Member member = new Member();
            member.setAccountId(Long.parseLong(smsSend.getAttr1()));
            member.setMobilePhone(smsSend.getAttr2());
            smsSendService.sendSms(smsSend, member);
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 会员模块——消息发送
     */
    @RequestMapping(value = "/addSendAccountLineNew")
    @ResponseBody
    public Map<String, Object> addSendAccountLineNew(@RequestBody SmsSend smsSend, HttpSession session,
                                                     HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<>();
        try {
            smsSendService.addSendAccontLineNew(smsSend.getId(), Long.parseLong(smsSend.getAttr1()), smsSend.getCorpid());
            result.put("success", true);
        } catch (ServiceException e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
            result.put("detailMessage", e.getMessage());
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
